﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Threading;
using System.Windows.Threading;
using System.Windows.Forms;

namespace TimeStart
{
    public partial class Update : Form
    {
        FileDownloaderApp.FileDownloader pdownload = new FileDownloaderApp.FileDownloader();
        WebClient cdownload = new WebClient();
        DispatcherTimer timer = new DispatcherTimer();
        DispatcherTimer tdownload = new DispatcherTimer();
        System.Uri outurl = new Uri("http://www.pietrosoft.altervista.org/timestart/version.txt");
        int appver = 1181, newver, counter = 0, downstate = -1;
        string appstringver = "v.1.1 build 81", outfile = System.IO.Path.GetTempPath() + "version.txt";
        string startuppath;

        public Update()
        {
            InitializeComponent();
        }

        private void Update_Load(object sender, EventArgs e)
        {
            this.Text = "TimeStart " + appstringver;
            startuppath = Environment.CurrentDirectory;
            lver.Text = appstringver;
            linfos.Text = "A small application to monitor computer's sessions.\n\n© 2011 Pietro Di Gennaro. All rights reserved.\n\nSpecial thanks to Brsev (http://brsev.deviantart.com/), user of Deviantart, creator of the main icon \n(Clock icon Part of: Token Light icon pack). We also thanks BN+ Discussions for the FileDownloader \nclass (http://www.codeproject.com/KB/vb/FileDownloader.aspx) included in the update module.";
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = new TimeSpan(0, 0, 0, 0, 1000);
            tdownload.Tick += new EventHandler(timerdownload_Tick);
            tdownload.Interval = new TimeSpan(0, 0, 0, 0, 10);
            try
            {
                if (File.Exists(System.IO.Path.GetTempPath() + "version.txt") == true)
                {
                    File.Delete(System.IO.Path.GetTempPath() + "version.txt");
                    timer.Start();
                }
                cdownload.DownloadFileAsync(outurl, outfile);
                cdownload.DownloadFileCompleted += (s, eArgs) =>
                {
                    StreamReader sreader = File.OpenText(outfile);
                    string temp = "";
                    temp = sreader.ReadLine();
                    int.TryParse(temp, out newver);
                    if (newver > appver)
                    {
                        temp = sreader.ReadLine();
                        loutput.Text = "New version avaible - v." + temp;
                        temp = sreader.ReadLine();
                        //sreader.Close();
                        pdownload.Files.Clear();
                        pdownload.LocalDirectory = System.IO.Path.GetTempPath();
                        pdownload.Files.Add(new FileDownloaderApp.FileDownloader.FileInfo(temp));
                        progressBar.Minimum = progressBar.Value = 0;
                        progressBar.Maximum = 100;
                        if (File.Exists(System.IO.Path.GetTempPath() + "\\timestart_latest.exe") == true)
                        {
                            File.Delete(System.IO.Path.GetTempPath() + "\\timestart_latest.exe");
                            timer.Start();
                        }
                        bupdate.Text = "Download";
                        bupdate.Enabled = true;
                        
                    }
                    else
                    {
                       
                        loutput.Text = "Your version is Up-To-Date. \nThanks for checking.";

                    }
                    sreader.Close();
                };
            }
            catch (Exception err)
            {
                loutput.Text = err.Message;
                
            }
            
        }
        private void timer_Tick(object sender, EventArgs e)
        {
            if (counter == 2)
            {
                timer.Stop();
                counter = 0;
            }
            else
                ++counter;
        }

        private void timerdownload_Tick(object sender, EventArgs e)
        {
            if (progressBar.Value == 100)
            {
                bupdate.Text = "UPDATE";
                tdownload.Stop();
                downstate = 1; //completed!!!
                loutput.Text = "DOWNLOAD COMPLETED.\nClick on Update to start the process.";
                bupdate.Focus();
            }
            else
            {
                loutput.Text = "Downloading ... " + (pdownload.CurrentFileProgress / 1024) + " of " + (pdownload.CurrentFileSize / 1024) + " KB, " + pdownload.DownloadSpeed / 1024 + " KB/s";
            }
            if (pdownload.CurrentFilePercentage() > 0)
                progressBar.Value = (int)pdownload.CurrentFilePercentage();
        }

        private void bupdate_Click_1(object sender, EventArgs e)
        {
            switch (downstate)
            {
                case -1: //download
                    progressBar.Visible = true;
                    tdownload.Start();
                    pdownload.Start();
                    downstate = 0;
                    bupdate.Text = "PAUSE";

                    break;
                case 0: //pause
                    tdownload.Stop();
                    bupdate.Text = "RESUME";
                    downstate = -1;

                    break;
                case 1: //completed
                    Process uprocess = new Process();
                    loutput.Text = "Click on Update to close this program and start the process.";
                    uprocess.StartInfo.FileName = System.IO.Path.GetTempPath() + "\\timestart_latest.exe";
                    timer.Start();
                    uprocess.Start(); //shell new downloaded update
                    Environment.Exit(0);
                    break;

            }
            
        }
        public static void checkforupdates()
        {
          
            WebClient cdownload = new WebClient();
            System.Uri outurl = new Uri("http://www.pietrosoft.altervista.org/timestart/version.txt");
            int appver = 1181, newver=0;
            string startuppath = Environment.CurrentDirectory, outfile = System.IO.Path.GetTempPath() + "version.txt";
            try
            {
                if (File.Exists(System.IO.Path.GetTempPath() + "version.txt") == true)
                
                    File.Delete(System.IO.Path.GetTempPath() + "version.txt");
             
                
                cdownload.DownloadFileAsync(outurl, outfile);
                cdownload.DownloadFileCompleted += (s, eArgs) =>
                {
                    StreamReader sreader = File.OpenText(outfile);
                    string temp = "";
                    temp = sreader.ReadLine();
                    
                    int.TryParse(temp, out newver);
                    if (newver > appver)
                    {
                        temp = sreader.ReadLine();
                        sreader.Close();
                        DialogResult answer = MessageBox.Show("A new version of TimeStart has been published. Do you want to update the application ?", "New version", MessageBoxButtons.YesNo);
                        if (answer == DialogResult.Yes)
                        {
                            Update fupdate = new Update();
                            fupdate.Show();
                            fupdate.Focus();
                        }
                    }
                    
                   
                };
            }
            catch (Exception ex)
            {
                //nothing to do ...
            }
            
           

        }
    }
}
